//
//  AddNewDeviceController.m
//  YSSmartHome
//
//  Created by yanghao on 2016/9/26.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "AddNewCameraController.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "LCOpenSDK_ConfigWifi.h"
#import "DeviceViewController.h"
#import "tommath.h"
#import "MQTTSessionManager.h"
#import "MQTTCoverTool.h"
#import "QRCoderViewController.h"
#import "GlobalConst.h"
#import "ZTDevice.h"

@interface AddNewCameraController ()
{
    LCOpenSDK_ConfigWIfi *m_configWifi;
    id info;
    
    id devView;
    LCOpenSDK_Api *m_hc;
    NSString      *m_strAccessToken;
}
@property (nonatomic, copy) NSString * m_textSSID;
@property (nonatomic, copy)NSString *m_strSerial;
@property (nonatomic, strong)UIView *coverView;
@property (nonatomic, strong)UITextField *textPasswd;
@property(nonatomic, strong)UILabel *m_lblHint;
@property(nonatomic, copy)NSString  *m_strPhone;


@property (nonatomic, strong)UIView *m_viewWifi;
@property (nonatomic, strong)UIImageView *m_imgWifi;
@property (nonatomic, strong)UILabel *m_lblwifi;
@property (nonatomic, strong)UIView *m_viewWired;
@property (nonatomic, strong)UIImageView *m_imgWired;
@property (nonatomic, strong)UILabel *m_lblWired;

@end

@implementation AddNewCameraController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    NSArray *interface = (__bridge id)CNCopySupportedInterfaces();
    for (NSString *interf in interface)
    {
        info = (__bridge id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interf));
        if (info && [info count])
        {
            break;
        }
    }
    //NSString *sID = @"SSID:";
    if (nil == info[@"SSID"] || 0 == [info[@"SSID"] length])
    {
        return;
    }
    //[sID stringByAppendingString:info[@"SSID"]];
    self.m_textSSID = info[@"SSID"];
   debugLogInfo(@"m_textSSID = %@", self.m_textSSID);
    m_configWifi = [[LCOpenSDK_ConfigWIfi alloc]init];
}

- (void)setupUI
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.view addSubview:self.m_viewWifi];
    [self.m_viewWifi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(10);
        make.leading.trailing.equalTo(self.view);
        make.height.equalTo(55);
    }];
    [self.m_viewWifi addSubview:self.m_imgWifi];
    [self.m_imgWifi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.m_viewWifi);
        make.leading.equalTo(self.m_viewWifi).offset(10);
        make.width.equalTo(45);
        make.height.equalTo(self.m_imgWifi.width);
    }];
    [self.m_viewWifi addSubview:self.m_lblwifi];
    [self.m_lblwifi mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.m_imgWifi);
        make.leading.equalTo(self.m_imgWifi.trailing).offset(10);
    }];
    
    [self.view addSubview:self.m_viewWired];
    [self.m_viewWired mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_viewWifi.bottom).offset(10);
        make.leading.trailing.equalTo(self.view);
        make.height.equalTo(self.m_viewWifi);
    }];
    
    [self.m_viewWired addSubview:self.m_imgWired];
    [self.m_imgWired mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.m_viewWired);
        make.leading.equalTo(self.m_viewWired).offset(10);
        make.width.equalTo(45);
        make.height.equalTo(self.m_imgWired.width);
    }];
    
    [self.m_viewWired addSubview:self.m_lblWired];
    [self.m_lblWired mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.m_imgWired);
        make.leading.equalTo(self.m_imgWired.trailing).offset(10);
    }];
    
    UITapGestureRecognizer *wifiTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onWifiClick)];
    [self.m_viewWifi addGestureRecognizer:wifiTap];
    UITapGestureRecognizer *wiredTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onWiredClick)];
    [self.m_viewWired addGestureRecognizer:wiredTap];
    UILabel *m_lblHint = [[UILabel alloc]init];
    m_lblHint.textAlignment = NSTextAlignmentCenter;
    m_lblHint.numberOfLines = 0;
    m_lblHint.font = [UIFont systemFontOfSize:14];
    m_lblHint.textColor = RGBColor(102, 102, 102);
    self.m_lblHint = m_lblHint;
    [self.view addSubview:m_lblHint];
    [m_lblHint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_viewWired.bottom).offset(30);
        make.centerX.equalTo(self.view);
    }];
}

- (void)coverViewClick:(UITapGestureRecognizer*)tapGes
{
    [self.coverView removeFromSuperview];
    self.coverView = nil;
}
-(void) setInfo:(LCOpenSDK_Api*)hc token:(NSString*)token devView:(id)view
{
    m_hc = hc;
    m_strAccessToken = [NSString stringWithString:token];
    devView = view;
}
- (void)sure{
    
    self.coverView.hidden = YES;
    [self.coverView removeFromSuperview];
    
    if (nil == self.m_strSerial || 0 == self.m_strSerial.length )
    {
        self.m_lblHint.text = @"请输入设备序列号";
        return;
    }
    if (nil == self.textPasswd.text || 0 == self.textPasswd.text.length || [self.textPasswd.text isEqualToString:@"请输入WiFi密码"])
    {
        self.textPasswd.text = @"";
    }
    RestApiService * restApiService = [RestApiService shareMyInstance];
    if ([restApiService checkDeviceBindOrNot:self.m_strSerial]) {
        self.m_lblHint.text = @"设备已被绑定";
        return;
    }
    
    UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"hint" message:@"请根据说明书开启设备配对键" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alter show];
    self.m_lblHint.text = @"开始无线配网";
    NSLog(@"[%@][%@][%@]",self.m_strSerial,info[@"SSID"],self.textPasswd.text);
    NSInteger iRet = [m_configWifi configWifiStart:self.m_strSerial ssid:info[@"SSID"] password:self.textPasswd.text secure:@"" callback:^(LC_ConfigWifi_Event event, void* userData) {
        if (userData == NULL) {
            return;
        }
        AddNewCameraController* pCont = (__bridge AddNewCameraController*)userData;
        if (pCont != nil)
        {
          [pCont notify:event];
        }
    } userData:self timeout:60];
    if (iRet < 0)
    {
        NSLog(@"smartconfig failed\n");
        return;
    }

}
- (void)onWiredClick
{
    if (nil == self.m_strSerial || 0 == self.m_strSerial.length )
    {
        self.m_lblHint.text = @"请输入设备序列号";
        return;
    }
    if (nil == self.textPasswd.text || 0 == self.textPasswd.text.length || [self.textPasswd.text isEqualToString:@"请输入WiFi密码"])
    {
        self.textPasswd.text = @"";
    }
    RestApiService * restApiService = [RestApiService shareMyInstance];
    if ([restApiService checkDeviceBindOrNot:self.m_strSerial]) {
        self.m_lblHint.text = @"设备已被绑定";
        return;
    }
    if (false == [restApiService checkDeviceOnline:self.m_strSerial]) {
        self.m_lblHint.text = @"设备未上线";
        return;
    }
    NSString* errMsg_Out;
    bool bRet = [restApiService bindDevice:self.m_strSerial Desc:&errMsg_Out];
    if (true == bRet) {
        self.m_lblHint.text = @"绑定成功";
        [self addNewLCCamera];
        [self setCameraName];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    else {
        self.m_lblHint.text = errMsg_Out;
    }

}
- (void)onWifiClick {
    
    UIView *coverView = [[UIView alloc]init];
    UITapGestureRecognizer * tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(coverViewClick:)];
    [coverView addGestureRecognizer:tapGes];
    coverView.backgroundColor = RGBAColor(0, 0, 0, 0.5);
    self.coverView = coverView;
    [self.navigationController.view addSubview:coverView];
    [coverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.navigationController.view);
    }];
    UIView *popView = [[UIView alloc]init];
    popView.backgroundColor = [UIColor whiteColor];
    [coverView addSubview:popView];
    [popView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(coverView);
        make.leading.equalTo(coverView).offset(30);
        make.trailing.equalTo(coverView.trailing).offset(-30);
        make.height.equalTo(220);
    }];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.text = @"无线添加";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.textColor = RGBColor(51, 51, 51);
    [popView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.trailing.equalTo(popView);
        make.height.equalTo(45);
    }];
    UIView *splitView = [[UIView alloc]init];
    splitView.backgroundColor = RGBColor(233, 233, 233);
    [popView addSubview:splitView];
    [splitView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.bottom);
        make.leading.trailing.equalTo(popView);
        make.height.equalTo(1);
    }];
    UILabel *wifiLabel = [[UILabel alloc]init];
    wifiLabel.text = [NSString stringWithFormat:@"WIFI网络: %@", self.m_textSSID];
    wifiLabel.textColor = RGBColor(51, 51, 51);
    [popView addSubview:wifiLabel];
    [wifiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(splitView.bottom);
        make.leading.equalTo(popView).offset(20);
        make.trailing.equalTo(popView).offset(-20);
        make.height.equalTo(45);
    }];

    UITextField *textPasswd = [[UITextField alloc]init];
    textPasswd.placeholder = @" 请输入 WIFI 密码";
    textPasswd.backgroundColor = RGBColor(238, 238, 238);
    self.textPasswd = textPasswd;
    [popView addSubview:textPasswd];
    [textPasswd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(wifiLabel.bottom);
        make.leading.equalTo(popView).offset(20);
        make.trailing.equalTo(popView).offset(-20);
        make.height.equalTo(45);
    }];
    UIButton *sureBtn = [[UIButton alloc]init];
    [sureBtn setBackgroundImage:[UIImage imageNamed:@"scene_circular_bg"] forState:UIControlStateNormal];
    [sureBtn setTitle:@"确定" forState:UIControlStateNormal];
    [sureBtn addTarget:self
                 action:@selector(sure) forControlEvents:UIControlEventTouchUpInside];
    [popView addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textPasswd.bottom).offset(20);
        make.leading.equalTo(textPasswd);
        make.trailing.equalTo(textPasswd);
        make.height.equalTo(45);
    }];
    
}


-(void) setInfo:(LCOpenSDK_Api*)hc token:(NSString*)token serial:(NSString *)serial phone:(NSString *)phone  devView:(id)view {
    m_hc = hc;
    m_strAccessToken = [NSString stringWithString:token];
    devView = view;
    self.m_strPhone = phone;
    self.m_strSerial = [serial copy];
}

-(void)notify:(NSInteger)event
{
    dispatch_async(dispatch_get_main_queue(), ^{
        RestApiService * restApiService = [RestApiService shareMyInstance];
        if (LC_ConfigWifi_Event_Success == event)
        {
            //配网成功后，等待设备上线，超时时间60S。
            time_t lBegin,lCur;
            NSInteger lLeftTime=60;
            time(&lBegin);
            lCur = lBegin;
            BOOL bOnline = NO;
            self.m_lblHint.text = @"准备绑定";
            [m_configWifi configWifiStop];
            if ([restApiService checkDeviceBindOrNot:self.m_strSerial])
            {
                self.m_lblHint.text = @"设备已被绑定";
                return;
            }
            while(lCur >= lBegin && lCur-lBegin < lLeftTime)
            {
                if (![restApiService checkDeviceOnline:self.m_strSerial])
                {
                    self.m_lblHint.text = [NSString stringWithFormat:@"等待时间%ld秒",lCur-lBegin];
                    usleep(5*1000*1000);
                    time(&lCur);
                    continue;
                }
                bOnline = YES;
                break;
            }
            if (NO == bOnline)
            {
                self.m_lblHint.text = @"设备未上线";
                return;
            }
            NSString * destOut;
            bool bRet = [restApiService bindDevice:self.m_strSerial Desc:&destOut];
            if (true == bRet)
            {
                self.m_lblHint.text = @"绑定成功";
                [self addNewLCCamera];
                [self setCameraName];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            else
            {
                self.m_lblHint.text = destOut;
            }
        }
        else
        {
            [m_configWifi configWifiStop];
            if (LC_ConfigWifi_Event_Timeout == event)
            {
                //超时后再检测一次是否上线，若上线则绑定
                if (true == [restApiService checkDeviceOnline:self.m_strSerial])
                {
                    NSString * destOut;
                    bool bRet = [restApiService bindDevice:self.m_strSerial Desc:&destOut];
                    if (true == bRet)
                    {
                        self.m_lblHint.text = @"绑定成功";
                        [self addNewLCCamera];
                        [self setCameraName];
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }
                    else
                    {
                        self.m_lblHint.text = destOut;
                    }
                }
                else
                {
                    self.m_lblHint.text = @"配网超时";
                }
            }
        }
    });
}


- (unsigned long)convert:(NSString *)str
{
    const char *aStr  = [str cStringUsingEncoding:NSUTF8StringEncoding];
    mp_int number1;
    mp_init(&number1);
    mp_read_radix(&number1, aStr, 36);
    char output[1000];
    mp_toradix(&number1, output, 16);
    unsigned long tmp =  mp_get_long(&number1);
    tmp  = (tmp & 0x0000ffffffffffffL) | (0x0601000000000000L);
    return tmp;
}
- (void)addNewLCCamera
{
    NSString *str1 = [self.m_strSerial substringToIndex:7];
    NSString *str2 = [self.m_strSerial substringFromIndex:11];
    NSString *newSerial = [NSString stringWithFormat:@"%@%@",str1,str2];
    uint64_t luid = [self convert:newSerial];
    XAITYPEAPSN apsn = kMQTTSessionManager.currentUser.currentBindApsn;

    
    NSMutableArray* datas  = [NSMutableArray array];
    XAITLV* tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&apsn length:sizeof(apsn)];
    [datas addObject:tlv];
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&luid length:sizeof(luid)];
    [datas addObject:tlv];
    uint32_t type = ZTDeviceTypeLCCamera;
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN bytes:&type length:sizeof(type)];
    [datas addObject:tlv];
    uint32_t version = 0;
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN bytes:&version length:sizeof(version)];
    [datas addObject:tlv];
    
    BOOL sleep = false;
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_BOOL bytes:&sleep length:sizeof(sleep)];
    [datas addObject:tlv];
    
    NSData* descriptionData = [@"摄像头" dataUsingEncoding:NSUTF8StringEncoding];
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void *)[descriptionData bytes] length:descriptionData.length];
    [datas addObject:tlv];
//    [kMQTTSessionManager sendDeviceDev:ZTDeviceTypeLCCamera verson:0xaab1 sleep:false fromApsn:fromApsn fromLuid:fromLuid];
    [kMQTTSessionManager.xai sendCMD:0x0B toApsn:apsn toLuid:kGATEWAYLUID datas:datas];
}

- (void)setCameraName
{
    NSString *str1 = [self.m_strSerial substringToIndex:7];
    NSString *str2 = [self.m_strSerial substringFromIndex:11];
    NSString *newSerial = [NSString stringWithFormat:@"%@%@",str1,str2];
    uint64_t luid = [self convert:newSerial];
    
    //是否在线
    XAITYPEAPSN devApsn = kMQTTSessionManager.currentUser.currentBindApsn;
    XAITYPELUID devLuid = luid;
    uint8_t status = 0xfe;
    uint8_t online = 1;
    NSMutableArray* onlineDatas = [NSMutableArray array];
    XAITLV* devApsnTlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_APSN bytes:&devApsn length:sizeof(devApsn)];
    [onlineDatas addObject:devApsnTlv];
    
    XAITLV* devLuidTlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_LUID bytes:&devLuid length:sizeof(devLuid)];
    [onlineDatas addObject:devLuidTlv];
    XAITLV* tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN bytes:&status length:sizeof(status)];
    [onlineDatas addObject:tlv];
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN bytes:&online length:sizeof(online)];
    [onlineDatas addObject:tlv];
    [kMQTTSessionManager.xai sendCMD:0x09 toApsn:kMQTTSessionManager.currentUser.currentBindApsn toLuid:kGATEWAYLUID datas:onlineDatas];
    
    //手机号
    NSMutableArray* phoneDatas = [NSMutableArray array];
    [phoneDatas addObject:devApsnTlv];
    [phoneDatas addObject:devLuidTlv];
    status = 0x01;
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_BIN_DIGITAL_UNSIGN bytes:&status length:sizeof(status)];
    [phoneDatas addObject:tlv];

    NSString * strData = [NSString stringWithFormat:@"%@.%@",self.m_strPhone,self.m_strSerial];
    tlv = [[XAITLV alloc]initWithType:XAI_DATA_TYPE_ASCII_TEXT bytes:(void*)[strData cStringUsingEncoding:NSUTF8StringEncoding] length:(int)[strData dataUsingEncoding:NSUTF8StringEncoding].length];
    [phoneDatas addObject:tlv];
    [kMQTTSessionManager.xai sendCMD:0x09 toApsn:kMQTTSessionManager.currentUser.currentBindApsn toLuid:kGATEWAYLUID datas:phoneDatas];
}

#pragma mark - lazy loading 

- (UIView *)m_viewWifi
{
    if (!_m_viewWifi) {
        _m_viewWifi = [[UIView alloc]init];
        _m_viewWifi.backgroundColor = [UIColor whiteColor];
    }
    return _m_viewWifi;
}

- (UIImageView *)m_imgWifi
{
    if (!_m_imgWifi) {
        _m_imgWifi  = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"security_addDevice_wifi"]];
        _m_imgWifi.userInteractionEnabled =YES;
    }
    return _m_imgWifi;
}

- (UILabel *)m_lblwifi
{
    if (!_m_lblwifi) {
        _m_lblwifi = [[UILabel alloc]init];
        _m_lblwifi.text = @"无线添加";
        _m_lblwifi.userInteractionEnabled = YES;
        _m_lblwifi.font = [UIFont systemFontOfSize:15];
        _m_lblwifi.textColor = RGBColor(51, 51, 51);
    }
    return _m_lblwifi;
}

- (UIView *)m_viewWired
{
    if (!_m_viewWired) {
        _m_viewWired = [[UIView alloc]init];
        _m_viewWired.backgroundColor = [UIColor whiteColor];
    }
    return _m_viewWired;
}

- (UIImageView *)m_imgWired
{
    if (!_m_imgWired) {
        _m_imgWired  = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"security_addDevice_wired"]];
        _m_imgWired.userInteractionEnabled =YES;
    }
    return _m_imgWired;
}

- (UILabel *)m_lblWired
{
    if (!_m_lblWired) {
        _m_lblWired = [[UILabel alloc]init];
        _m_lblWired.text = @"有线添加";
        _m_lblWired.userInteractionEnabled = YES;
        _m_lblWired.font = [UIFont systemFontOfSize:15];
        _m_lblWired.textColor = RGBColor(51, 51, 51);
    }
    return _m_lblWired;
}

@end
